/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package entities;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author ditakurniawaty
 */
public class MemberQuery {
    public MemberQuery() {
        emf = Persistence.createEntityManagerFactory("persistence");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public boolean check(String username) {
        boolean result = false;
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("SELECT count(o) FROM Member AS o WHERE o.username=:username");
            q.setParameter("username", username);
            int jumlahUser = ((Long) q.getSingleResult()).intValue();
            if (jumlahUser > 0) {
                result = true;
            }
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return result;
    }

    public Members getMember(String username) {
        Members user = null;
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("SELECT object(o) FROM Member AS o WHERE o.username=:user");
            q.setParameter("user", username);
            user = (Members) q.getSingleResult();
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return user;
    }

    public List<Members> getMember() {
        int adminStat = 0;
        List<Members> users = new ArrayList<Members>();

        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("SELECT object(o) FROM Member AS o WHERE o.adminStat=:admst");
            q.setParameter("admst", adminStat);
            users = q.getResultList();

        } finally {
            if (em != null) {
                em.close();
            }
        }
        return users;
    }

    public void editMember(Members user) {
        EntityManager em = getEntityManager();
        em.getTransaction().begin();
        try {
            em.merge(user);
            em.getTransaction().commit();
        } catch (Exception e) {
            em.getTransaction().rollback();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void create(Members user) {
        EntityManager em = getEntityManager();
        em.getTransaction().begin();
        try {
            em.persist(user);
            em.getTransaction().commit();
        } catch (Exception e) {
            em.getTransaction().rollback();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

}
